<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Score</title>
    <style>
      .red {
        color: red;
      }
    </style>
  </head>

  <body>
    <script src="../src/Vue2/vue.js"></script>

    <div id="app">
      <h1 align="center">成绩单</h1>
      <table align="center">
        <thead>
          <tr>
            <th>编号</th>
            <th>科目</th>
            <th>成绩</th>
            <th>操作</th>
          </tr>
        </thead>

        <tbody v-if="list.length > 0">
          <tr v-for="(item, index) in list" :key="item.id">
            <td align="center">{{ index + 1 }}</td>
            <td align="center">{{ item.name }}</td>
            <td align="center" :class="{red: item.score < 60}">
              {{ item.score }}
            </td>
            <td>
              <a href="#" @click="deleteSubject(item.id)">删除</a>
            </td>
          </tr>
        </tbody>

        <tbody v-else>
          <tr>
            <td colspan="3">暂无数据</td>
          </tr>
        </tbody>

        <tfoot></tfoot>
      </table>

      <h2 align="center">添加新科目</h2>
      <input
        type="text"
        v-model.trim="subject"
        placeholder="请输入科目"
        align="center"
      />
      <br />
      <input
        type="text"
        v-model.trim.number="score"
        placeholder="请输入成绩"
        align="center"
      />
      <br />
      <button @click="addSubject" align="center">添加</button>
      <br />
      <h3 align="center">总分：{{ sum }}</h3>
      <h3 align="center" v-if="this.list.length > 0">
        平均分：{{ parseInt(sum / this.list.length) }}
      </h3>
      <h3 align="center" v-else>平均: 0</h3>
    </div>

    <script>
      const app = new Vue({
        el: "#app",
        data: {
          list: [
            { id: 1, name: "语文", score: 90 },
            { id: 2, name: "数学", score: 90 },
            { id: 3, name: "英语", score: 90 },
          ],
          subject: "",
          score: "",
        },
        methods: {
          deleteSubject(id) {
            this.list = this.list.filter((item) => item.id !== id);
          },
          addSubject() {
            // 往后加是push，往前加是unshift
            if (!this.subject || !this.score) {
              alert("科目和成绩不能为空");
              return;
            }
            if (typeof this.score !== "number") {
              alert("成绩必须是数字");
              return;
            }
            this.list.push({
              id: +new Date(), // 为了保证id的唯一性，使用时间戳
              name: this.subject,
              score: this.score,
            });
            this.subject = "";
            this.score = "";
          },
        },
        computed: {
          sum: {
            get() {
              return this.list.reduce((prev, cur) => prev + cur.score, 0);
            },

            set() {},
          },
        },
      });
    </script>
  </body>
</html>
